package com.mall.rabbitmq.demo1;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author hyt
 * @date 2021/10/26
 */
@Component
public class QueueListener {

    @RabbitListener(queuesToDeclare = @Queue("boot_queue"))
    public void receiveMsg(String msg, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel){
        System.out.println("收到消息:"+msg);
    }

    @RabbitListener(queuesToDeclare = @Queue("boot_worker"))
    public void receiveWorkMsg(String msg, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
        System.out.println("工作者模式:"+msg);
        // multiple true 返回消息确认该消息已被消费 false 不返回
        channel.basicAck(deliveryTag,false);
    }

    //Pub/Sub模式
    @RabbitListener(bindings = @QueueBinding(value = @Queue,exchange = @Exchange(name = "boot_pubsub",type = "fanout")))
    public void pubsubMsg(String msg, @Header(AmqpHeaders.DELIVERY_TAG)long deliveryTag, Channel channel) throws Exception {
        System.out.println("收到消息1:"+msg);
        channel.basicAck(deliveryTag,false);
    }

    //Routing模式 接收对应key里面的数据
    @RabbitListener(bindings = @QueueBinding(value = @Queue(name = "boot_rounting_queue"),
            exchange = @Exchange(name = "boot_rounting_exchange",type = "direct"),key = {"info"}
    ))
    public void rountingInfoMsg(String msg, @Header(AmqpHeaders.DELIVERY_TAG)long deliveryTag, Channel channel) throws Exception {
        System.out.println("error&info 收到消息:"+msg);
        channel.basicAck(deliveryTag,false);
    }

    //Routing模式 接收对应key里面的数据
    @RabbitListener(bindings = @QueueBinding(value = @Queue(name = "boot_rounting_queue"),
            exchange = @Exchange(name = "boot_rounting_exchange",type = "direct"),key = {"error"}
    ))
    public void rountingErrorMsg(String msg, @Header(AmqpHeaders.DELIVERY_TAG)long deliveryTag, Channel channel) throws Exception {
        System.out.println("error&info 收到消息:"+msg);
        channel.basicAck(deliveryTag,false);
    }

    //Topic模式 接受可匹配通配符
    @RabbitListener(bindings = @QueueBinding(value = @Queue("boot_topic_queue"),
            exchange = @Exchange(name = "boot_topic_exchange",type = "topic"),key = "order.*"
    ))
    public void topicMsg(String msg, @Header(AmqpHeaders.DELIVERY_TAG)long deliveryTag, Channel channel) throws Exception {
        System.out.println("topic收取消息:"+msg);
        channel.basicAck(deliveryTag,false);
    }
}
